// 文章分类控制器
const db = require('../config/db');

// @desc    创建分类
// @route   POST /api/categories
// @access  Private (假设只有登录用户可以创建)
const createCategory = async (req, res) => {
  const { name } = req.body;
  if (!name) {
    return res.status(400).json({ message: '分类名称为必填项' });
  }

  try {
    const [result] = await db.query('INSERT INTO categories (name) VALUES (?)', [name]);
    res.status(201).json({ id: result.insertId, name });
  } catch (error) {
    if (error.code === 'ER_DUP_ENTRY') {
      return res.status(409).json({ message: '分类名称已存在' });
    }
    console.error(error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// @desc    获取所有分类（分页）
// @route   GET /api/categories
// @access  Public
const getAllCategories = async (req, res) => {
  const page = parseInt(req.query.page, 10) || 1;
  const limit = parseInt(req.query.limit, 10) || 10;
  const offset = (page - 1) * limit;

  try {
    const [[{ total }]] = await db.query('SELECT COUNT(*) as total FROM categories');
    const [categories] = await db.query('SELECT * FROM categories ORDER BY id DESC LIMIT ? OFFSET ?', [limit, offset]);
    
    res.json({
      data: categories,
      meta: {
        totalItems: total,
        totalPages: Math.ceil(total / limit),
        currentPage: page,
        itemsPerPage: limit
      }
    });
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Server error' });
  }
};

// @desc    更新分类
// @route   PUT /api/categories/:id
// @access  Private
const updateCategory = async (req, res) => {
  const { id } = req.params;
  const { name } = req.body;

  if (!name) {
    return res.status(400).json({ message: '分类名称为必填项' });
  }

  try {
    const [result] = await db.query('UPDATE categories SET name = ? WHERE id = ?', [name, id]);
    if (result.affectedRows === 0) {
      return res.status(404).json({ message: '分类未找到' });
    }
    res.json({ id, name });
  } catch (error) {
    if (error.code === 'ER_DUP_ENTRY') {
      return res.status(409).json({ message: '分类名称已存在' });
    }
    console.error(error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// @desc    删除分类
// @route   DELETE /api/categories/:id
// @access  Private
const deleteCategory = async (req, res) => {
  const { id } = req.params;
  try {
    const [result] = await db.query('DELETE FROM categories WHERE id = ?', [id]);
    if (result.affectedRows === 0) {
      return res.status(404).json({ message: '分类未找到' });
    }
    res.status(204).send(); // 204 No Content
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: '服务器错误' });
  }
};

module.exports = {
  createCategory,
  getAllCategories,
  updateCategory,
  deleteCategory,
};